package br.com.lh.urabuilder.command
{
	import br.com.lh.urabuilder.domain.xml.UraXml;
	import br.com.lh.urabuilder.event.SaveUraEvent;
	import br.com.lh.urabuilder.model.UraModelLocator;
	import br.com.lh.urabuilder.view.ActionComponent;
	
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	public class SaveUraCommand implements ICommand
	{
		private var dbServer:RemoteObject  = new RemoteObject("dbDestination");		
		
		private var modelLocator:UraModelLocator;
			
		public function SaveUraCommand(){
			modelLocator=UraModelLocator.getInstance();
			
		}
		
		public function execute(event:CairngormEvent):void{
			var uraXml:UraXml = modelLocator.xmlManager.getUraXml();
			uraXml.alias = SaveUraEvent(event).alias;
			uraXml.uraExtension = SaveUraEvent(event).extensionNumber;
			uraXml.xmlString = uraXml.xml.toString();
			var componentCanvasChildren:ArrayCollection = UraModelLocator.getInstance().viewManager.getComponents();
			uraXml.clearViewArrays();
			for (var i:int = 0;i < componentCanvasChildren.length;i++){
				if (componentCanvasChildren.getItemAt(i) is ActionComponent){
					var component:ActionComponent = ActionComponent(componentCanvasChildren[i]);
					uraXml.insert(int(component.id),component.x,component.y,component.textArea.text,component.databaseId);
				}
			}
			var sessionId:String = SaveUraEvent(event).sessionId;
			dbServer.saveUra(uraXml,sessionId);
			dbServer.saveUra.addEventListener("result",function(e:ResultEvent): void {
			updateId(e,uraXml);
			});
		}
		
		private function updateId(event:ResultEvent,uraXml:UraXml):void	{
			uraXml.uraId = String(event.result);
			uraXml.clearViewArrays();
			modelLocator.xmlManager.setUraXml(uraXml);
		}
		

	}
}